import { useState, useEffect } from 'react';
import { useModel } from 'umi';
import { Table, message, Select, Button, Space } from 'antd';
const { Option } = Select;
import {
  teacherService,
  experimentScoreService, experimentCourseService,
  courseService, experimentTotalScoreService
} from '@/service';
import { executeActionAfterReq } from '@/util/errorHandle';
import styles from './index.less';

function ExperimentCoursePage() {
  const { teacher } = useModel('useTeacher');
  const [cIds, setCIdsData] = useState([]);
  const [studentData, setStudentData] = useState([]);
  const [selectOption, setSelectOption] = useState([]);
  const [theId, setTheId] = useState('');
  const [filters, setFilters] = useState([]);
  useEffect(() => {
    getAllTeacher();
  }, [teacher]);
  useEffect(() => {
    getAllCourse();
  }, [cIds]);

  const getAllTeacher = async () => {
    const res = await teacherService.getAllTeacher().catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, () => {
      setCIdsData((res?.data
        ?.find((item: any) => teacher?.tId == item?.tId)
        ?.cIds || '')
        ?.split(',')
        ?.filter((item: any) => item)
        ?.map((item: any) => Number(item))
      );
    })
  }

  const getAllCourse = async () => {
    const res = await courseService.getAllCourse().catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, async () => {
      setSelectOption(res?.data
        .filter((item: any) => cIds.includes(item?.cId))
        .map((item: any) => ({
          id: item.cId,
          title: item.cTitle,
        })));
    });
  }

  // 根据当前的课程 id 请求学生数据
  const reqData = async (id = theId) => {
    if (!id) {
      message.error('请选择课程');
      return;
    }
    const res = await experimentTotalScoreService.getAllExperimentTotalScore().catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(res, () => {
      const data = res?.data
      .filter((item: any) => id == item?.cId)
      .map((item: any) => ({
        sId: item.sId,
        cId: item.cId,
        totalScore: item.totalScore,
        sName: item.Student.sName,
        tcId: item.Student.tcId,
      }));
      setStudentData(data);
      setFilters(Array
        .from(new Set(data.map((item: any) => item.tcId)))
        .map((item: any) => ({
          text: item,
          value: item,
        })));
    });
  }
  const onChange = (id: string) => {
    setTheId(id);
    reqData(id);
  }

  const calcTotalScore = async () => {
    let ecIds = [];
    const courseRes = await courseService.getAllCourse().catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(courseRes, () => {
      ecIds = courseRes?.data.find((item: any) => theId == item.cId)?.ecIds
        ?.split(',')?.map(item => Number(item)) || [];
    })

    let experimentScore = [];
    const experimentScoreRes = await experimentScoreService.getAllExperimentScore().catch(() => {
      message.error('请求错误');
    });
    executeActionAfterReq(experimentScoreRes, () => {
      experimentScore = experimentScoreRes?.data.filter((item: any) => ecIds?.includes(item.ecId)) || [];
    })

    const calcStudentData = studentData.map((item: any) => ({
      ...item,
      totalScore: calcScoreOfStudent(item, experimentScore)
    }))
    console.log("🚀 ~ file: index.tsx ~ line 90 ~ calcStudentData ~ calcStudentData", calcStudentData)

    Promise.all(calcStudentData.map(async (item: any) => {
      const res = await experimentTotalScoreService.updateExperimentTotalScore(item).catch(() => {
        message.error('请求错误');
      });
      executeActionAfterReq(res, () => {
        message.info(`${item?.sId} ${item?.sName} 成绩计算完成！`);
      })
    }))

    reqData();
  }

  // 计算该学生的该门课程成绩
  const calcScoreOfStudent = (student: any, experimentScore: any) => {
    const studentExperimentScore = experimentScore.filter((item: any) => student.sId == item.sId);

    let ecDifficultyDegree = 0;
    studentExperimentScore.forEach((item: any) => {
      ecDifficultyDegree += Number(item?.ExperimentCourse?.ecDifficultyDegree);
    });

    let res = 0;
    studentExperimentScore.forEach((item: any) => {
      res += Number(item?.score * item?.ExperimentCourse?.ecDifficultyDegree / ecDifficultyDegree);
    });
    return Math.floor(res);
  }

  const columns = [
    {
      title: '学号',
      dataIndex: 'sId',
      key: 'sId',
      sorter: (a: any, b: any) => a.sId - b.sId,
      sortDirections: ['ascend'],
    },
    {
      title: '姓名',
      dataIndex: 'sName',
      key: 'sName',
      sorter: (a: any, b: any) => a.sName - b.sName,
      sortDirections: ['ascend'],
    },
    {
      title: '班级编号',
      dataIndex: 'tcId',
      key: 'tcId',
      filters,
      onFilter: (value: any, record: any) => record.tcId == value,
    },
    {
      title: '成绩',
      dataIndex: 'totalScore',
      key: 'totalScore',
      sorter: (a: any, b: any) => a.totalScore - b.totalScore,
      sortDirections: ['ascend'],
    },
  ]
  
  return (
    <div className={styles.student}>
      <div className={styles.course}>
        <span>任教的课程: </span>
        <Select
          placeholder="请选择课程"
          onChange={onChange}
          className={styles.select}
        >
          {
            selectOption.map((course: any) => <Option value={course?.id}>{`${course?.id}: ${course?.title}`}</Option>)
          }
        </Select>
        <Button type="primary" htmlType="button" className={styles.button} onClick={() => reqData()}>
          确认课程
        </Button>
        <Button type="primary" htmlType="button" className={styles.button} onClick={() => calcTotalScore()}>
          计算成绩
        </Button>
      </div>
      <Table dataSource={studentData} columns={columns} style={{minHeight: "400px"}} />
    </div>
  );
}

export default ExperimentCoursePage;
